package twitter;
import java.io.IOException;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Helper {
	/**
	 * Do Xpath-expression on a xml-string
	 * @param string The XML-String
	 * @param xpath The Xpath-expression
	 * @return NodeList Results nodelist
	 */
	public static NodeList parseXMLWithXPath(String string, String xpath) {		
		try {
			CustomXpath cx = new CustomXpath(string);
			return cx.execute(xpath);
		}
		catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static Document getDOMFromXML(String xml) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
    	fact.setValidating(true);
    	fact.setIgnoringElementContentWhitespace(true);
    	
    	DocumentBuilder builder = fact.newDocumentBuilder();
    	Document document = builder.parse(xml);
    	
    	return document;
	}
	
	/**
	 * Convert date, which was formated from twitter, to the date that suitable to database
	 * @param date Date received from twitter
	 * @return String New date as string
	 */
	public static String convertDateAndTime(String date) {
		String[] dates = date.split(" ");

		String month = dates[1];
		String day = dates[2];
		String time = dates[3];
		String year = dates[5];
		
		if(Integer.parseInt(day) <= 9) {
			day = "0"+day;
		}
		day = day.replaceAll("00", "0");
		
		HashMap<String, String> months = new HashMap<String, String>(12);
		months.put("Jan","01");
		months.put("Feb","02");
		months.put("Mar","03");
		months.put("Apr","04");
		months.put("May","05");
		months.put("Jun","06");
		months.put("Jul","07");
		months.put("Aug","08");
		months.put("Sep","09");
		months.put("Oct","10");
		months.put("Nov","11");
		months.put("Dec","12");
		
		String dateString = year+"-"+months.get(month)+"-"+day+" "+time;
		
		return dateString;
	}
	
	/**
	 * System.out.println() simplified
	 * @param string The string to be printed
	 */
	public static void log(String string) {
		System.out.println(string);
	}
}
